package cn.com.zsw.gblog.modules.user.service.impl;

import cn.com.zsw.gblog.constants.SysConstants;
import cn.com.zsw.gblog.modules.user.entity.GbUserEntity;
import cn.com.zsw.gblog.modules.user.entity.RoleEntity;
import cn.com.zsw.gblog.modules.user.mapper.RoleMapper;
import cn.com.zsw.gblog.modules.user.mapper.UserMapper;
import cn.com.zsw.gblog.modules.user.service.GbUserRoleService;
import cn.com.zsw.gblog.modules.user.service.GbUserService;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * (gb_sys_user)表服务实现类
 *
 * @author shiwangzhou
 * @since 2020-09-17 16:50:14
 */
@Service("gbSysUserService")
public class GbUserServiceImpl extends ServiceImpl<UserMapper, GbUserEntity> implements GbUserService {
    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    GbUserRoleService gbUserRoleService;

    /**
     * desc: 根据昵称新增一个用户
     *
     * @param nickname 昵称
     * @return void
     * @author: shiwangZhou
     * @date: 2020-09-24 11:24
     * @param: nickName 昵称
     */
    @Override
    public GbUserEntity createNewUser(String nickname, String avatar) {
        GbUserEntity gbUser = new GbUserEntity();
        gbUser.setUsername(nickname);
        gbUser.setPassword(new BCryptPasswordEncoder().encode(SysConstants.DEFAULT_PASSWORD));
        gbUser.setAccountNonExpired(true);
        gbUser.setAccountNonLocked(true);
        gbUser.setCredentialsNonExpired(true);
        gbUser.setEnabled(true);
        gbUser.setAuthorities(Sets.newHashSet());
        gbUser.setRoles(Lists.newArrayList());
        gbUser.setId(IdUtil.createSnowflake(1,1).nextId());
        gbUser.setNickname(nickname);
        gbUser.setAvatar(avatar);
        gbUser.setCreateTime(new Date());
        gbUser.setUpdateTime(new Date());
        gbUser.setStatus(1);
        userMapper.insert(gbUser);
        //新增默认角色关联
        RoleEntity roleEntity = roleMapper.selectOne(Wrappers.<RoleEntity>lambdaQuery().eq(RoleEntity::getName, SysConstants.DEFAULT_ROLE_NAME).eq(RoleEntity::getStatus, 1));
        Assert.notNull(roleEntity, "默认角色不存在,请联系管理员");
        gbUserRoleService.setRole(gbUser.getId(), roleEntity.getId());
        return gbUser;
    }
}